package com.media.publish.fragment;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.baselibrary.Constants;
import com.baselibrary.activity.BaseFragment;
import com.baselibrary.manager.DialogManager;
import com.baselibrary.permission.PermissionCollection;
import com.baselibrary.permission.PermissionsUtils;
import com.baselibrary.permission.callback.PermissionsCall;
import com.baselibrary.utils.CommonUtil;
import com.baselibrary.utils.OnClickListener;
import com.baselibrary.utils.ScreenUtils;
import com.baselibrary.utils.VideoDownloadUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.signature.ObjectKey;
import com.media.R;
import com.media.databinding.FragmentBigImagerBinding;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXVodPlayer;
import com.xinlan.imageeditlibrary.editimage.view.imagezoom.ImageViewTouchBase;

/*大图模式*/
public class ViewImagerFragment extends BaseFragment implements ITXLivePlayListener {


    private FragmentBigImagerBinding mBing;
    private String mUrl;
    private int mType;
    public static final int VIDEO_TYPE = 101;//视频
    public static final int IMG_TYPE = 102;//图片
    private View mBingRoot;
    private int mSlidePro;
    protected boolean isVisible;
    private boolean isPrepared;
    private boolean isFirst = true;

//    private ShareHelp shareHelp = ActivityRouter.getARouterInterface(ActivityRouter.ACTIVITY.SHARE_HELP);
    private String mPictureWatermark;
    private static final String TAG = "onHiddenChanged";

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            lazyLoad();
            videoResume();
        } else {
            isVisible = false;
            videoPause();
        }
    }

    public static ViewImagerFragment newInstance(Bundle bundle) {
        ViewImagerFragment fragment = new ViewImagerFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_big_imager;
    }

    @Override
    protected void init() {
        if (getArguments() != null) {
            mUrl = getArguments().getString("url");
            mType = getArguments().getInt(Constants.WIKI_IMGPAGER_TYPE);
            mPictureWatermark = getArguments().getString(Constants.WIKI_PICTURE_WATERMARK);
        }
        mBing = (FragmentBigImagerBinding) getDataBinding();
        isPrepared = true;
        lazyLoad();
    }

    protected void lazyLoad() {
        if (!isPrepared || !isVisible || !isFirst) {
            return;
        }

        try {
            initData();
        } catch (Exception e) {
            e.getMessage();
        }
        isFirst = false;
    }

    private void initData() {
        if (VIDEO_TYPE == mType) {
            mBing.previewProgressBar.setVisibility(View.GONE);
            mBing.ivImager.setVisibility(View.GONE);
            mBing.rlVideo.setVisibility(View.VISIBLE);
            mBing.pbBigImager.setVisibility(View.VISIBLE);
            mBing.llVideoProgress.setVisibility(View.VISIBLE);
            initPlayerView(mUrl);
            mBing.rlVideo.setOnLongClickListener(v -> {
                DialogManager.showSavePictureDialog(getActivity(), true, (view, object) -> PermissionsUtils.getInstance().chekPermissions(getActivity(), PermissionCollection.FILE.getPermissionList(), new PermissionsCall() {
                    @Override
                    public void permissionsPass() {
                        VideoDownloadUtil.download(getActivity(), mUrl, ".mp4");
                    }
                }));
                return false;
            });
        } else {
            mBing.previewProgressBar.setVisibility(View.VISIBLE);
            mBing.pbBigImager.setVisibility(View.GONE);
            mBing.rlVideo.setVisibility(View.GONE);
            mBing.llVideoProgress.setVisibility(View.GONE);
            mBing.ivImager.setVisibility(View.VISIBLE);

            RequestOptions userAvatarOptions = new RequestOptions()
                    .signature(new ObjectKey(System.currentTimeMillis()));
            Glide.with(getActivity())
                    .applyDefaultRequestOptions(userAvatarOptions)
                    .asBitmap().load(mUrl)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                            try {
                                mBing.previewProgressBar.setVisibility(View.GONE);
                                if (!bitmap.isRecycled()) {
                                    int mBitHeight = bitmap.getHeight();
                                    int mScreenHeight = ScreenUtils.getScreenHeight(getActivity());
                                    Glide.with(requireActivity()).load(bitmap).into(mBing.ivImager);
                                    if (mBitHeight >= mScreenHeight * 5) {
                                        mBing.ivImager.setLongGraph(true);
                                    } else {
                                        mBing.ivImager.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
                                    }
                                }
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
            mBing.ivImager.setOnLongClickListener(v -> {
                DialogManager.showSavePictureDialog(getActivity(), false, new OnClickListener() {
                    @Override
                    public void onClick(View view, Object object) {
                        PermissionsUtils.getInstance().chekPermissions(getActivity(), PermissionCollection.FILE.getPermissionList(), new PermissionsCall() {
                            @Override
                            public void permissionsPass() {
                                if (!TextUtils.isEmpty(mPictureWatermark)) {
                                    mUrl = mUrl + mPictureWatermark;//说明是加水印的图
                                }
                                VideoDownloadUtil.download(getActivity(), mUrl, ".jpg");
                            }
                        });
                    }
                });
                return false;
            });
            mBing.ivImager.setSingleTapListener(() -> {
                if (getActivity() != null) {
                    getActivity().finish();
                }
            });
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (isPrepared) {
            return;
        }
        videoResume();

    }

    public void videoResume() {
        if (mVodPlayer != null) {
            mVodPlayer.resume();
            mBing.videoPlay.setSelected(true);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        videoPause();
    }

    public void videoPause() {
        if (mVodPlayer != null) {
            mVodPlayer.pause();

            mBing.videoPlay.setSelected(false);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        videoPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    /**
     * SDK player 相关
     */
    private TXVodPlayer mVodPlayer = null;

    private void initPlayerView(final String url) {

        mBing.videoView.setLogMargin(12, 12, 110, 60);
        mBing.videoView.showLog(false);
        mBing.videoView.setKeepScreenOn(true);
        if (mVodPlayer == null) {
            mVodPlayer = new TXVodPlayer(getContext());
        }

        mVodPlayer.setVodListener(new ITXVodPlayListener() {
            @Override
            public void onPlayEvent(TXVodPlayer txVodPlayer, int i, Bundle bundle) {

                switch (i) {
                    case TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED://视频播放开始
                        mBing.pbBigImager.setVisibility(View.GONE);
                        break;
                    case TXLiveConstants.PLAY_EVT_PLAY_PROGRESS:
                        int progress = bundle.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                        int duration = bundle.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);
                        if (mBing.progress.getMax() != duration) {
                            mBing.totalDuration.setText(CommonUtil.Formatter.formatTime((duration)));
                            mBing.progress.setMax(duration);
                        }
                        mBing.currentDuration.setText(CommonUtil.Formatter.formatTime((progress)));
                        mBing.progress.setProgress(progress);
                        break;
                }
            }

            @Override
            public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {

            }
        });
        mVodPlayer.setPlayerView(mBing.videoView);
        mVodPlayer.setAutoPlay(true);
        mVodPlayer.setPlayListener(this);
        mVodPlayer.enableHardwareDecode(false); // 是否使用硬解码
        mVodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);// player 渲染角度
        mVodPlayer.setRenderMode(TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION);//player 渲染模式
        int result = mVodPlayer.startVodPlay(url); // result返回值：0 success;  -1 empty url; -2 invalid url; -3 invalid playType;
        if (result == 0) {
            mBing.videoPlay.setSelected(true);
        }

        mBing.rlVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBing.videoPlay.setVisibility(mBing.videoPlay.isShown() ? View.GONE : View.VISIBLE);
                if (mBing.videoPlay.isShown()) {
                }
            }
        });
        mBing.videoPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVodPlayer != null) {
                    if (mVodPlayer.isPlaying()) {
                        mVodPlayer.pause();
                        mBing.videoPlay.setSelected(false);
                    } else {
                        mVodPlayer.resume();
                        mBing.videoPlay.setSelected(true);
                    }
                }
            }
        });
        mBing.progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mSlidePro = seekBar.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //手指抬起获取当前SeekBar进度
                if (mVodPlayer != null) {
                    mVodPlayer.seek(mSlidePro / 1000);
                    mBing.videoPlay.setSelected(true);
                }
            }
        });
    }


//    private void showVideoProgressInfo() {
//        if (mVodPlayer != null) {
//            int curPosition = (int) mVodPlayer.getCurrentPlaybackTime();
//            int duration = (int) mVodPlayer.getPlayableDuration();
//            int bufferPosition = (int) mVodPlayer.getBufferDuration();
//            mBing.currentDuration.setText(CommonUtil.Formatter.formatTime((int) (curPosition * 1000)));
//            mBing.totalDuration.setText(CommonUtil.Formatter.formatTime((int) (duration * 1000)));
//            mBing.progress.setMax((int) duration);
//            mBing.progress.setSecondaryProgress((int) bufferPosition);
//            mBing.progress.setProgress((int) curPosition);
//            if (((int) (curPosition * 1000) != 0) && (int) (curPosition * 1000) == (int) (duration * 1000)) {//播放结束
//                mBing.videoPlay.setSelected(false);
//                mBing.videoPlay.setVisibility(View.VISIBLE);
//            }
//        }
//    }


    @Override
    public void onPlayEvent(int i, Bundle bundle) {

    }

    @Override
    public void onNetStatus(Bundle bundle) {

    }


}
